package net.wwang.blog.util;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import net.wwang.blog.pojo.User;

import java.util.HashMap;
import java.util.Map;

/**
 * @author WangWei
 * @date 2020/8/14
 */
@Slf4j
public class ClaimUtil {
    private static final String ID = "id";
    private static final String USERNAME = "username";
    private static final String EMAIL = "email";
    private static final String ROLES = "roles";
    private static final String AVATAR = "avatar";
    private static final String SIGN = "sign";
    private static final String TEL = "tel";

    public static Map<String,Object> userToClaims(User userFromDb){
        Map<String,Object> claims = new HashMap<>();
        claims.put(ID,userFromDb.getId());
        claims.put(USERNAME,userFromDb.getUsername());
        claims.put(EMAIL,userFromDb.getEmail());
        claims.put(ROLES,userFromDb.getRoles());
        claims.put(AVATAR,userFromDb.getEmail());
        claims.put(SIGN,userFromDb.getSign());
        claims.put(TEL,userFromDb.getTel());
        log.info("The user is converted to claims.");
        return claims;
    }

    public static User claimsToUser(Claims claims){
    User user = new User();
        String id = (String) claims.get(ID);
        user.setId(id);
        String userName = (String) claims.get(USERNAME);
        user.setUsername(userName);
        String roles = (String) claims.get(ROLES);
        user.setRoles(roles);
        String avatar = (String) claims.get(AVATAR);
        user.setAvatar(avatar);
        String email = (String) claims.get(EMAIL);
        user.setEmail(email);
        String sign = (String) claims.get(SIGN);
        user.setSign(sign);
        String tel = (String) claims.get(TEL);
        user.setTel(tel);
        log.info("After claims are converted to user");
        return user;
    }
}
